package com.itheima.web.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Freeze;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.AdminService;

import com.itheima.service.db.FreezeService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.VideoService;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;

/**
 * @author Guanxing
 * @date 2021/9/30
 */
@Component
public class UserManager {

    @Reference
    private FreezeService freezeService;

    @Reference
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private VideoService videoService;

    @Reference
    private MovementService movementService;

    @Reference
    private CommentService commentService;

    //查询用户
    public PageBeanVo findUsers(Integer page, Integer pagesize) {
        PageBeanVo pageBeanVo = userInfoService.findUsersByPage(page, pagesize);
        List<UserInfo> items = (List<UserInfo>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(items)) {
            for (UserInfo userInfo : items) {
                //判断缓存中是否存在冻结时间
                Boolean timeFlag = stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FREEZE_TIME, userInfo.getId()));
                if (!timeFlag) {//缓存中不存在冻结时间
                    userInfo.setUserStatus("1");//用户状态修改为正常
                    //修改userInfo
                    userInfoService.update(userInfo);
                }
            }
        }
        return pageBeanVo;
    }

    //查询用户详情
    public UserInfoVo findById(Long userId) {
        UserInfo userInfo = userInfoService.findById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    //查询视频列表
    public PageBeanVo findVideoByUserId(Integer pageNumber, Integer pagesize, Long uid) {
        PageBeanVo pageBeanVo = videoService.findVideoByUid(pageNumber,pageNumber,uid);

        List<Video> items = (List<Video>) pageBeanVo.getItems();
        List<VideoManagerVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Video video : items) {
                VideoManagerVo vo = new VideoManagerVo();
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                //转换
                BeanUtil.copyProperties(userInfo,vo);
                BeanUtil.copyProperties(video,vo);
                vo.setSignature(video.getText());

                voList.add(vo);
            }
        }

        pageBeanVo.setItems(voList);

        return pageBeanVo;
    }

    //查询动态列表
    public PageBeanVo findMovementList(Integer pageNumber, Integer pageSize, Long uid, Integer stateInt) {
        PageBeanVo pageBeanVo = movementService.findMovementsByUserIdAndState(pageNumber,pageSize,uid,stateInt);

        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        List<MovementVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //查询用户信息
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                //封装数据
                MovementVo vo = new MovementVo();
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);
                //时间的替换
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(movement.getCreated());
                String createDate = simpleDateFormat.format(date);
                vo.setCreateDate(createDate);

                voList.add(vo);
            }
        }

        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    //查询动态详情
    public MovementVo findMovementById(String movementId) {
        Movement movement = movementService.findMovementByMovementId(movementId);

        MovementVo vo = new MovementVo();
        UserInfo userInfo = userInfoService.findById(movement.getUserId());
        vo.setUserInfo(userInfo);
        vo.setMovement(movement);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(movement.getCreated());
        String createDate = simpleDateFormat.format(date);
        vo.setCreateDate(createDate);

        return vo;
    }

    //查询评论列表
    public PageBeanVo findCommentByMovementId(Integer page, Integer pagesize, String messageID) {
        PageBeanVo pageBeanVo = commentService.findCommentList(page, pagesize, messageID);

        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> voList = new ArrayList<>();

        if(CollectionUtil.isNotEmpty(items)){
            for (Comment comment : items) {
                CommentVo vo = new CommentVo();
                BeanUtil.copyProperties( comment , vo );
                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                vo.setNickname(userInfo.getNickname());
                vo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date( comment.getCreated() )));
                voList.add(vo);
            }
        }

        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    //用户冻结操作
    public Map freeze(Freeze freeze) {
        //1.获取userId
        Long userId = freeze.getUserId();
        //2.获取冻结时间
        Integer freezingTime = freeze.getFreezingTime();
        //缓存中的key
        String keyTime = StrUtil.format(ConstantUtil.FREEZE_TIME, userId);
        if (freezingTime == 1) { //冻结3天
            stringRedisTemplate.opsForValue().set(keyTime, "1", Duration.ofDays(3));
        } else if (freezingTime == 2) { //冻结7天
            stringRedisTemplate.opsForValue().set(keyTime, "2", Duration.ofDays(7));
        } else if (freezingTime == 3) { //永久冻结
            stringRedisTemplate.opsForValue().set(keyTime, "3");
        }
        //3.获取冻结范围
        Integer freezingRange = freeze.getFreezingRange();
        //缓存中的key
        String keyRange = StrUtil.format(ConstantUtil.FREEZE_Range, userId);
        if (freezingRange == 1) { //冻结登录
            stringRedisTemplate.opsForValue().set(keyRange,"1");
        } else if (freezingRange == 2) { //冻结发言
            stringRedisTemplate.opsForValue().set(keyRange,"2");
        } else if (freezingRange == 3) { //冻结发布动态
            stringRedisTemplate.opsForValue().set(keyRange,"3");
        }
        //4.查userInfo
        UserInfo userInfo = userInfoService.findById(userId);
        userInfo.setUserStatus("2");
        //5.保存userInfo
        userInfoService.update(userInfo);
        //6.保存或修改freeze
        Freeze freezeById = freezeService.findByUserId(userId);
        if (freezeById == null) {//保存
            freezeService.save(freeze);
        } else {//修改
            freezeService.update(freeze);
        }
        //7.返回
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return map;
    }

    //用户解冻操作
    public Map unfreeze(Freeze freeze) {
        //1.修改userInfo
        UserInfo userInfo = userInfoService.findById(freeze.getUserId());
        userInfo.setUserStatus("1");
        userInfoService.update(userInfo);
        //2.修改freeze表数据
        Freeze freezeById = freezeService.findByUserId(freeze.getUserId());
        freezeById.setReasonsForThawing(freeze.getReasonsForThawing());
        freezeService.update(freezeById);
        //3.删除缓存
        String keyTime = StrUtil.format(ConstantUtil.FREEZE_TIME, freeze.getUserId());
        String keyRange = StrUtil.format(ConstantUtil.FREEZE_Range, freeze.getUserId());
        stringRedisTemplate.delete(keyTime);
        stringRedisTemplate.delete(keyRange);
        //4.返回
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return map;
    }

}
